package com.fingard.dsp.bank.directbank.ccb41;

import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IAuthorizeForRec;
import com.fingard.dsp.bank.reqrespobj.authforrec.*;
import com.fingard.dsp.bank.reqrespobj.authforrec.detail.RetAtsQryRecAuthInfoDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by F on 2018/7/3.
 */
public class CCB41AuthorizeForRec extends CCB41Base implements IAuthorizeForRec {


    @Override
    public RetAtsAuthForRec d_auth(ReqAuthForRec p_req) throws Exception {
        //从共享目录下载契约，身份证
        RetAtsAuthForRec tmpRetAts = new RetAtsAuthForRec(p_req.reqHeader);
        boolean isUploadSucc = false;
        if (p_req.readRecord()) {
            try {
                boolean isCanAuth = isCanAuth(p_req.readedDetail.oppAct);
                if (!isCanAuth) {
                    throw new Exception("存在处理中的签约情况或者该账号已全部签约，请核查！");
                }
            }catch (Exception ex){
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = ex.getMessage();
                ex.printStackTrace();
                tmpRetAts.writeRetToATS();
                return tmpRetAts;
            }
            try {
                XmlTextWriter xmlWriter = new XmlTextWriter();
                CCB41Header bankHeader = new CCB41Header();
                bankHeader.tranId = "0001";
                bankHeader.tranDate = Format.Date8Format.format(new Date());
                String compId = getBankConfig().getValueAsString("compid");
                bankHeader.compId = compId;
                bankHeader.seqNo = p_req.reqSeqID;
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("Body");
                xmlWriter.writeElementString("Name", p_req.readedDetail.oppActName, true);//姓名
                xmlWriter.writeElementString("Idcardno", p_req.readedDetail.certNum, true);//证件号码
                xmlWriter.writeElementString("Phone", p_req.readedDetail.reqReserved4, true);//手机号
                xmlWriter.writeElementString("Account", p_req.readedDetail.oppAct, true);//账号
                xmlWriter.writeElementString("Max_amt", getBankConfig().getMapValueByKey("Max_amt", p_req.ownAct), true);//单笔限额
                xmlWriter.writeElementString("Reserve1", "", true);//保留1
                xmlWriter.writeElementString("Reserve2", "", true);//保留2
                xmlWriter.writeElementString("Reserve3", "", true);//保留3
                xmlWriter.writeElementString("Reserve4", "", true);//保留4
                xmlWriter.writeElementString("Reserve5", "", true);//保留5
                xmlWriter.writeEndDocument();
                String fileName = String.format("%1$s%2$s_AuthInfo.txt", getBankConfig().getValueAsString("saveDir"), p_req.readedDetail.oppAct);
                //项目编号|申请流水id|name|证件号码|手机号|账号|收方账号
                String context = compId + "|" + p_req.reqSeqID + "|" + p_req.readedDetail.oppActName + "|" +
                        p_req.readedDetail.certNum + "|" + p_req.readedDetail.reqReserved4 + "|" + p_req.readedDetail.oppAct +
                        "|" + p_req.ownAct;
                synchronized (CCB41Base.class) {
                    FileHelper.writeFile(fileName, context, getCharset());
                }
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        tmpRetAts.respCode = "0";
                        String retCode = tmpBkReader.getFirstText("/Root/Head/Retcode");
                        String retMsg = tmpBkReader.getFirstText("/Root/Head/Retmsg");
                        if ("0000".equals(retCode)) {
                            tmpRetAts.serialNo = p_req.reqSeqID;
                            tmpRetAts.retCode = "2";
                        } else {
                            tmpRetAts.retCode = "1";
                        }
                        tmpRetAts.retMsg = retMsg;
                    } else {
                        tmpRetAts.respCode = "-1";
                        tmpRetAts.respInfo = tmpSbMsg.toString();
                    }
                } else {
                    tmpRetAts.respCode = "-1";
                    tmpRetAts.respInfo = tmpStrRet[1];
                }
            } catch (Exception e) {
                tmpRetAts.respCode = "-1";
                tmpRetAts.respInfo = e.getMessage();
                e.printStackTrace();
            }
        } else {
            tmpRetAts.respCode = "-1";
            tmpRetAts.respInfo = "detail信息为空";
        }
        tmpRetAts.writeRetToATS();
        return tmpRetAts;
    }

    private boolean isCanAuth(String oppAct) throws Exception {
        boolean isCanAuth = false;
        String [] recPayAccs =getBankConfig().getValueAsString("ownAct").split(",");
        if(recPayAccs==null||recPayAccs.length==0){
            throw new Exception("未配置商户账号");
        }
        for(String recPayAcc:recPayAccs) {
            String fileName = getBankConfig().getValueAsString("saveDir")+oppAct+File.separator+recPayAcc+".txt";
            if (FileHelper.existFile(fileName)) {
                //批量编号|申请流水id|name|证件号码|手机号|账号|收方账号|项目编号|签约会员号|签约情况（1-签约成功，2-签约失败，3-处理中）
                String authStr = FileHelper.readFileText(fileName, getCharset());
                String[] authlist = authStr.split("\\|");
                if(authlist.length==10){
                    if("2".equals(authlist[9])){
                        isCanAuth=true;
                    }else if("3".equals(authlist[9])){
                        throw new Exception("文件："+fileName+" 签约处理中，请到我的银行卡刷新签约状态");
                    }
                }else{
                    throw new Exception("签约文件异常");
                }
            } else {
                isCanAuth = true;
            }
        }
        return isCanAuth;
    }

    public boolean uploadAuthFile(String directDir,FtpSet p_ftpSet,SmbFile[] smbFiles) throws Exception {
        SftpPortClient sftp = new SftpPortClient(p_ftpSet);
        for(SmbFile smbFile:smbFiles) {

            InputStream in = new SmbFileInputStream(smbFile);
            smbFile.length();

            FtpReceiver ftpReceiver = sftp.uploadFile(directDir, in, smbFile.getName());
          if (!ftpReceiver.isCompleted) {
            return false;
            }
        }
        return true;
    }

    @Override
    public RetAtsQryAuthForRec d_qry_auth(ReqQryAuthForRec p_req) throws Exception {
//        RetAtsQryAuthForRec tmpRetAts = new RetAtsQryAuthForRec(p_req.reqHeader);
//        tmpRetAts.writeStart();
//        tmpRetAts.reqSeqID =p_req.reqSeqID;
//        try{
//            XmlTextWriter xmlTextWriter = new XmlTextWriter();
//            CCB041Header bankHeader = new CCB041Header();
//            bankHeader.tranId ="0003";
//            bankHeader.tranDate =Format.Date8Format.format(new Date());
//            bankHeader.compId ="";
//            bankHeader.seqNo=p_req.reqSeqID;
//            writeCommonHeader(xmlTextWriter,bankHeader);
//            xmlTextWriter.writeElementString("Signid", "");//签约会员号
//            xmlTextWriter.writeElementString("Name","");//姓名
//            xmlTextWriter.writeElementString("Idcardno","");//证件号码
//            xmlTextWriter.writeElementString("Phone","");//手机号
//            xmlTextWriter.writeElementString("Account","");//账号
//            xmlTextWriter.writeEndDocument();
//            String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());
//            if (tmpStrRet[0].length() == 0) {
//                StringBuilder tmpSbMsg = new StringBuilder();
//                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
//                if (tmpBkReader != null) {
//                    String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/Retcode");
//                    String tmpRetInfo = tmpBkReader.getFirstText("/Root/Head/Retmsg");
//                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
//                        RetAtsQryAuthForRecDetail tmpDetail = new RetAtsQryAuthForRecDetail();
//                        String signState = tmpBkReader.getFirstText("/Root/Body/Signstat");
//                        if("00".equals(signState)){
//                            tmpDetail.transState ="2";
//
//                        }else if("01".equals(signState)){
//                            tmpDetail.transState ="3";
//
//                        }else if("02".equals(signState)){
//                            tmpDetail.transState ="3";
//
//                        }else if("03".equals(signState)){
//                            tmpDetail.transState ="2";
//
//                        }else if("04".equals(signState)){
//                            tmpDetail.transState ="3";
//                        }else if("05".equals(signState)){
//                            tmpDetail.transState ="3";
//                        }else{
//                            throw new Exception("未知的签约状态"+signState);
//                        }
//                        tmpDetail.contractNo = tmpBkReader.getFirstText("/Root/Body/Phone");
//                        tmpDetail.oppActName = tmpBkReader.getFirstText("/Root/Body/Name");
//                        tmpDetail.oppAct = tmpBkReader.getFirstText("/Root/Body/Account");
//                        tmpRetAts.writeRetDetail(tmpDetail);
//                    } else {
//                        tmpRetAts.respCode = "-1";
//                        tmpRetAts.respInfo = tmpRetInfo;
//                    }
//                }else{
//                    tmpRetAts.respCode = "-1";
//                    tmpRetAts.respInfo = tmpSbMsg.toString();
//                }
//            } else {
//                tmpRetAts.respCode = "-1";
//                tmpRetAts.respInfo = "数据为空";
//            }
//        }catch (Exception ex) {
//            tmpRetAts.respCode = "-1";
//            tmpRetAts.respInfo = ex.getMessage();
//            ex.printStackTrace();
//        }
//        if (tmpRetAts.getWriteRdCount() <= 0) {
//            tmpRetAts.writeRetHead();
//        }
//        tmpRetAts.writeAfterDetail();
//        return tmpRetAts;
        return null;
    }

    @Override
    public RetAtsQryRecAuthInfo d_qry_authInfo(ReqQryRecAuthInfo p_req) throws Exception {
        RetAtsQryRecAuthInfo tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
        tmpRetAts.ownAct = p_req.ownAct;
        String tmpRespCode = "";
        String tmpRespInfo = "";
        try {
            String signFile = getBankConfig().getValueAsString("saveDir")+p_req.oppAct+File.separator+p_req.ownAct+".txt";
            String authInfoStr = FileHelper.readFileText(signFile, getCharset());
//                String authInfoStr = "HT001|1649409473|杨海勇|150202196605120616|13904723631|4340620420047033|44001668840050955835|440289580|HT001201812251649409473|3";
            if (StringHelper.isNullOrEmpty(authInfoStr)) {
                throw new Exception("签约会员文件不存在或者文件内容为空");
            }
            //批量编号|申请流水id|name|证件号码|手机号|账号|收方账号|项目编号|签约会员号|签约情况（1-签约成功，2-签约失败，3-处理中）
            String[] authInfo = authInfoStr.split("\\|");
//            String compId = getBankConfig().getMapValueByKey("PROTOCOL", p_req.ownAct);
            CCB41Header bankHeader = new CCB41Header();
            bankHeader.tranId = "0003";
            bankHeader.tranDate = Format.Date8Format.format(new Date());
            bankHeader.compId = authInfo[7];
            bankHeader.seqNo = authInfo[1];//申请时的流水号
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //写入通用的头部节点
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("Body");
            //验证码错误
            try {
                xmlWriter.writeElementString("Signid", authInfo[8], true);//签约会员号
            }catch (ArrayIndexOutOfBoundsException e){
                tmpRetAts.respCode = "0";
                tmpRetAts.respInfo = "签约会员号为空,签约失败";
                tmpRetAts.writeAfterDetail();
                return tmpRetAts;
            }
            xmlWriter.writeElementString("Name", authInfo[2], true);//姓名
            xmlWriter.writeElementString("Idcardno", authInfo[3], true);//证件号码
            xmlWriter.writeElementString("Phone", authInfo[4], true);//手机号
            xmlWriter.writeElementString("Account", authInfo[5], true);//账号
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/Root/Head/Retcode");
                    String tmpRetInfo = tmpBkReader.getFirstText("/Root/Head/Retmsg");
                    if (tmpRetCode != null && tmpRetCode.equals("0000")) {
                        RetAtsQryRecAuthInfoDetail tmpDetail = new RetAtsQryRecAuthInfoDetail();
                        String signstat = tmpBkReader.getFirstText("/Root/Body/Signstat");
                        if ("00".equals(signstat)) {
                            tmpRetAts.respCode = "0";
                            tmpRetAts.respInfo = "签约成功";
                            tmpDetail.authDateFrom = tmpBkReader.getFirstText("/Root/Body/Signdate");
                            tmpDetail.oppAct = tmpBkReader.getFirstText("/Root/Body/Account");
                            tmpDetail.oppActName = tmpBkReader.getFirstText("/Root/Body/Name");
                            tmpDetail.queryTag = p_req.queryTag;
                            tmpRetAts.writeRetDetail(tmpDetail);
                            authInfoStr = authInfoStr.substring(0,authInfoStr.length()-1);
                            authInfoStr =authInfoStr+1;
                            synchronized (CCB41SendSmsCode.class) {
                                FileHelper.writeFile(signFile, authInfoStr, getCharset());
                            }
                        } else if ("08".equals(signstat)) {
                            tmpRetAts.respCode = "0";
                            tmpRetAts.respInfo = "银行处理中";
                            tmpDetail.authDateFrom = tmpBkReader.getFirstText("/Root/Body/Signdate");
                            tmpDetail.oppAct = tmpBkReader.getFirstText("/Root/Body/Account");
                            tmpDetail.oppActName = tmpBkReader.getFirstText("/Root/Body/Name");
                            tmpDetail.queryTag = "2";
                            tmpRetAts.writeRetDetail(tmpDetail);
                            //资料有误
                        } else if ("02".equals(signstat) || "06".equals(signstat)||"04".equals(signstat)||"05".equals(signstat)) {
                            tmpRespCode = "0";
                            tmpRespInfo = "签约失败";
                            authInfoStr = authInfoStr.substring(0,authInfoStr.length()-1);
                            authInfoStr =authInfoStr+2;
                            synchronized (CCB41SendSmsCode.class) {
                                FileHelper.writeFile(signFile, authInfoStr, getCharset());
                            }
                        } else {
                            tmpRespCode = "0";
                            tmpRespInfo = "异常状态：" + signstat;
                        }
                    } else {
                        tmpRespCode = "0";
                        tmpRespInfo = tmpRetInfo;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRespCode = "-1";
                tmpRespInfo = "数据为空";
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            tmpRetAts = new RetAtsQryRecAuthInfo(p_req.reqHeader);
            tmpRetAts.respCode = tmpRespCode;
            tmpRetAts.respInfo = tmpRespInfo;
            tmpRetAts.ownAct = p_req.ownAct;
        } else {
            tmpRetAts.respCode = "0";
            tmpRetAts.respInfo = tmpRespInfo;
        }
        tmpRetAts.writeAfterDetail();
        return tmpRetAts;
    }
}
